<?php

namespace app\api\service;

use app\api\model\ExaminationAnswer;
use app\api\model\ExaminationPaper;
use app\api\model\ExaminationQuestion;
use app\api\model\UserChallenge;
use app\api\model\UserExamination;
use app\api\model\UserList;

class UserService
{
    public static function getUserInfo($deviceId)
    {
        $userInfo = UserList::getUserInfoByDeviceId($deviceId);
        if (!$userInfo) {
            $userInfo = UserList::createUserInfoByDeviceId($deviceId);
        }
        return [200, '操作成功', [
            'user_id' => $userInfo['id'],
            'user_name' => $userInfo['name'],
            'user_avatar' => dealImage($userInfo['avatar']),
            'user_level' => $userInfo['level'],
            'user_sign' => $userInfo['sign'],
            'user_exp' => $userInfo['exp'],
            'user_login' => $userInfo['login_day'] ?? 1,
            'user_token' => UserList::createUserToken($userInfo['id'], $userInfo['device_id']),
        ]];
    }

    public static function getUserChallenge($userInfo)
    {
        $todayChallenge = UserChallenge::getRecordToday($userInfo['id']);
        if (!$todayChallenge) {
            $yesterdayChallenge = UserChallenge::getRecordYesterday($userInfo['id']);
            if (!$yesterdayChallenge) {
                UserList::updateUserChallenge($userInfo['id'], 0);
            }
        }
        $examinationId = ExaminationPaper::getDailyExamination();
        $difficulty = (int)ExaminationQuestion::getAvgDifficultyByPid($examinationId);
        $userInfo = UserList::getUserInfoByUserId($userInfo['id']);
        return [200, '操作成功', [
            'challenge_day' => $userInfo['challenge_day'],
            'challenge_progress' => $userInfo['challenge_day'] >= 7 ? 100 : bcmul(bcdiv($userInfo['challenge_day'], 7, 2), 100),
            'today_challenge' => (bool)$todayChallenge,
            'today_pass' => $todayChallenge['pass'] ?? false,
            'today_score' => $todayChallenge['score'] ?? false,
            'exam_id' => $examinationId,
            'exam_difficulty' => $difficulty,
            'date' => date('m-d'),
        ]];
    }

    public static function getUserRecord($userInfo)
    {
        $examNumber = UserExamination::countUserExamination($userInfo['id']);
        $wrongNumber = ExaminationAnswer::countUserAnswer($userInfo['id']);
        $collectNumber = 0;
        return [200, '操作成功', [
            'exam_number' => $examNumber,
            'wrong_number' => $wrongNumber,
            'collect_number' => $collectNumber,
        ]];
    }
}